package zhieasy.cn.xpu_helper.controller.common;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import zhieasy.cn.common.utils.result.ResultUtils;
import zhieasy.cn.common.utils.result.StatusCode;
import zhieasy.cn.common.vo.PermissionRoleParmVo;
import zhieasy.cn.common.vo.ResultVO;
import zhieasy.cn.common.vo.TreeVo;
import zhieasy.cn.model.common.Permission;
import zhieasy.cn.model.common.WechatUser;
import zhieasy.cn.model.vo.mean.MakeMenuTree;
import zhieasy.cn.service.common.PermissionService;
import zhieasy.cn.service.common.RolePermissionService;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author DaHang
 * @date 2020/8/13 21:11
 */
@RestController
@RequestMapping("/common/security")
@Api(tags = "common模块，权限相关配置（目前无用）")
public class PermissionController {


    @Autowired
    PermissionService permissionService;

    @Autowired
    RolePermissionService rolePermissionService;

    /**
     * 获取所有模块列表
     * @param
     * @return
     */
    @PreAuthorize("hasRole('student')")
    @RequestMapping(value = "/getModelList", method = RequestMethod.POST)
    public ResultVO getMenuList() {
        SecurityContext ctx = SecurityContextHolder.getContext();
        Authentication auth = ctx.getAuthentication();
        WechatUser user = (WechatUser) auth.getPrincipal();

        QueryWrapper<Permission> query = new QueryWrapper<>();
        query.lambda().orderByAsc(Permission::getOrderNum);
        List<Permission> list = permissionService.list(query);
        List<Permission> menuList = null;
        if(!list.isEmpty()){
            menuList = MakeMenuTree.makeTree(list, 0L);
        }
        return ResultUtils.success("成功", StatusCode.SUCCESS_CODE, menuList);
    }

    /**
     * 新增模块权限
     */
    @RequestMapping(value = "/addPermission",method = RequestMethod.POST)
    public ResultVO addPermission(@RequestBody Permission permission){
        permissionService.save(permission);
        return ResultUtils.success("新增成功");
    }

    /**
     * 根据id查询模块
     * @param permission
     * @return
     */
    @RequestMapping(value = "getModelById",method = RequestMethod.POST)
    public ResultVO getMenuById(@RequestBody Permission permission){
        Permission model = permissionService.getById(permission.getPermissionId());
        return ResultUtils.success("成功",model);
    }


    /**
     * 根据id更新模块权限
     * @param permission
     * @return
     */
    @RequestMapping(value = "/editSave",method = RequestMethod.POST)
    public ResultVO editSave(@RequestBody Permission permission){
        permission.setCreateTime(new Date().getTime());
        boolean res = permissionService.updateById(permission);
        if(res){
            return ResultUtils.success("更新成功");
        }else{
            return ResultUtils.error("更新失败");
        }
    }


    /**
     * 删除权限
     * @return
     */
    @RequestMapping(value = "/deleteModel",method = RequestMethod.POST)
    public ResultVO deleteEntity(@RequestBody Permission permission){
        boolean b = permissionService.removeById(permission.getPermissionId());
        if(b){
            return ResultUtils.success("删除成功!");
        }else{
            return ResultUtils.error("删除失败!");
        }
    }

    /**
     * 新增权限，顶级模块
     * @return
     */
    @RequestMapping(value = "/getParentTree",method = RequestMethod.POST)
    public ResultVO getParentTree(){
        QueryWrapper<Permission> query = new QueryWrapper<>();
        //查询一下权限属于路由或按钮级别的菜单
        query.lambda().eq(Permission::getType,"0").or().eq(Permission::getType,"1");
        //查询出来放到list里面
        List<Permission> list = permissionService.list(query);
        //整个list
        List<TreeVo> listTree = new ArrayList<>();
        //先弄一个，叫顶级菜单的
        TreeVo parentTree = new TreeVo();
        parentTree.setId(0L);
        parentTree.setPid(-1L);
        parentTree.setName("顶级菜单");
        parentTree.setOpen(true);
        parentTree.setChecked(false);
        listTree.add(parentTree);
        //遍历查询出来的
        if(list.size() > 0){
            for(Permission p : list){
                if(p != null){
                    TreeVo tree = new TreeVo();
                    tree.setId(p.getPermissionId());
                    tree.setPid(p.getParentId());
                    tree.setName(p.getLabel());
                    tree.setOpen(true);
                    tree.setChecked(false);
                    listTree.add(tree);
                }
            }
        }
        return ResultUtils.success("成功",listTree);
    }

    //保存权限
    @RequestMapping(value = "/saveAssignRole",method = RequestMethod.POST)
    public ResultVO saveAssignRole(@RequestBody PermissionRoleParmVo parmVo){
        if(parmVo != null && !parmVo.getList().isEmpty()){
            List<TreeVo> list = parmVo.getList();
            Long roleId = parmVo.getRoleId();
            List<Long> ids = list.stream().filter(item -> item != null).map(item ->
                item.getId()).collect(Collectors.toList());
            rolePermissionService.saveAssignRole(roleId,ids);
            return ResultUtils.success("分配成功!");
        }else{
            return ResultUtils.error("请选择权限!");
        }
    }

}
